import { handle_socket_massage } from "@/handle";
import { socket_host } from "@/plugins/host";


let socket_port = 9998;
// let socket_host = "127.0.0.1";

// socket_host = "10.73.113.246";

let warning_port = 9997;



let web_socket = null;

let eventss = {};

let data_socket_time = 10 * 1000; //毫秒数
let data_local_time = 0;
let data_timer = null; //计时器。


function formatter_socket_time(time_str) {
  return (
    time_str.slice(0, 4) +
    "-" +
    time_str.slice(4, 6) +
    "-" +
    time_str.slice(6, 8) +
    " " +
    time_str.slice(8, 10) +
    ":" +
    time_str.slice(10, 12) +
    ":" +
    time_str.slice(12, 14)
  );
}

function websocket_init() {
  try {
    websocket_close();
    web_socket = new WebSocket("ws://" + socket_host + ":" + socket_port);

  } catch (e) {
    console.log("%cwebsocket_初始化失败_>>", "color:skyblue", e);
  }

  web_socket.onopen = websocket_on_open;
  web_socket.onmessage = websocket_on_message;
  web_socket.onclose = websocket_on_close;
  web_socket.onerror = websocket_on_error;

}

function websocket_on_open() {
  console.log(socket_port + "connecting ..");

}

function websocket_on_message(res, socket_fn) {

  let res_data = JSON.parse(res.data);

  window.sessionStorage.setItem('socket_status', "true");



  if (window.my_console == 1) {
    console.log(socket_port + ":onmessages: " + "%cwebsocket_收到数据 res.data_res_data", "color:blue", res_data);
  }




  // 创建一个名为 'my-event' 的 CustomEvent
  eventss = new CustomEvent('socket_data', {
    detail: {
      data: res_data,
    },
    bubbles: true,
    cancelable: true
  });

  window.dispatchEvent(eventss);

  eventss = null;


  // socket_fn(res);
}

function websocket_on_close() {

  if (window.my_console == 1) {
    console.log('on_close-9998');
  }

}

function websocket_on_error(err) {

  if (window.my_console == 1) {
    console.log(`%c ${socket_port} error ..`, "color:red", err);
  }

}

function websocket_send(cmd, arr_param) {
  var data_formatter = {
    cmd: cmd,
    data: arr_param,
  };

  console.log("%cwebsocket_send 参数", "color:skyblue", data_formatter);

  web_socket.send(JSON.stringify(data_formatter));
}

function websocket_send_new(param) {
  // var data_formatter = {
  //   cmd: cmd,
  //   data: arr_param,
  // };

  websocket_on_close();

  console.log("%cwebsocket_send .js参数", "color:green", param);

  if (web_socket == null) {
    websocket_init();
  }

  setTimeout(() => {
    web_socket.send(JSON.stringify(param));
  }, 1000)


}

function websocket_close() {
  web_socket && web_socket.close();
  web_socket = null;

  if (window.my_console == 1) {
    console.log(`获取数据的 ${socket_port} socket主动关闭`);
  }

}

function websocket_reconect() {
  websocket_close();
  websocket_init();

  if (window.my_console == 1) {
    console.log(`${socket_port} socket-主动重连---`);
  }


  try {

    setTimeout(() => {
      let params = JSON.parse(window.sessionStorage.getItem("socket_param") == null ? '{}' : window.sessionStorage.getItem("socket_param"));
      if (window.my_console == 1) {
        console.log("重连后发一次请求", params);
      }

      if (params.cmd == undefined) {

        if (window.my_console == 1) {
          console.log("没有找到socket请求的缓存参数", params)
        }

      } else {
        websocket_send_new(params);
      }

    }, 1800)

  } catch (e) {

    if (window.my_console == 1) {
      console.log(e, "websocket_reconect-重连后发生错误",)
    }

  }

}

console.log(
  "获取数据的 的socket 需要主动发送参数,根据断开的page记录对应的pageId"
);

export {
  web_socket,
  websocket_init,
  websocket_on_open,
  websocket_on_message,
  websocket_on_close,
  websocket_on_error,
  websocket_send,
  websocket_send_new,
  websocket_close,
  websocket_reconect,
};

// let param = {
//   cmd: cmd,
//   data: data_arr
// }

// 只读属性 readyState 表示连接状态，可以是以下值：

// 0 - 表示连接尚未建立。

// 1 - 表示连接已建立，可以进行通信。

// 2 - 表示连接正在进行关闭。

// 3 - 表示连接已经关闭或者连接不能打开。
